package com.pdsu.alumni.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdsu.alumni.common.annotation.NoAuthentication;
import com.pdsu.alumni.common.result.Result;
import com.pdsu.alumni.pojo.CommonUser;
import com.pdsu.alumni.pojo.Faculty;
import com.pdsu.alumni.pojo.Mail;
import com.pdsu.alumni.pojo.User;
import com.pdsu.alumni.service.*;
import com.pdsu.alumni.util.DateUtil;
import com.pdsu.alumni.util.MD5;
import com.pdsu.alumni.util.TencentMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: alumni
 * @description: 校友前端控制器
 * @author: Acerola
 * @create: 2022-01-10 08:49
 **/
@Api(tags = "校友前端控制层")
@Slf4j
@RestController
@RequestMapping("/commonuserui")
public class CommonUserUI {

    @Autowired
    private ICommonUserService commonUserService;
    @Autowired
    private ISchoolrollService schoolrollService;
    @Autowired
    private IProduceService produceService;
    @Autowired
    private TencentMessage tencentMessage;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MD5 md5;
    @Autowired
    private UserService userService;
    @Autowired
    private IFacultyService facultyService;

    @ApiOperation(value = "账号密码登录")
    @PostMapping("/loginByPwd")
    @NoAuthentication
    @ResponseBody
    @CrossOrigin
    public Result loginByPwd(String phone, String pwd) {
        QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 1);
        queryWrapper.eq("state", 0);
        queryWrapper.eq("cuser_phone", phone);
        queryWrapper.eq("cuser_password", pwd);
        CommonUser commonUser = commonUserService.getOne(queryWrapper);
        if (commonUser == null) {
            return new Result().error("用户不存在,请检查账号或密码");
        }
        return new Result().success("登录成功");
    }

    @ApiOperation(value = "获取短信验证码")
    @GetMapping("/msgcode")
    @ResponseBody
    @CrossOrigin
    @NoAuthentication
    public Result<?> register(String num) {
        String[] strings = {num};
        String code = tencentMessage.messageSend(strings);
        redisTemplate.opsForValue().set(num + "msgcode", code, 60 * 5, TimeUnit.SECONDS);
        return new Result<>().success().put(code);
    }

    @ApiOperation(value = "短信验证码登录")
    @PostMapping("/loginByMsg")
    @NoAuthentication
    @ResponseBody
    @CrossOrigin
    public Result loginByMsg(String phone, String code) {
        QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 1);
        queryWrapper.eq("state", 0);
        queryWrapper.eq("cuser_phone", phone);
        CommonUser commonUser = commonUserService.getOne(queryWrapper);
        String msgcode = (String) redisTemplate.opsForValue().get(phone + "msgcode");
        if (!code.equals(msgcode)) {
            return new Result().error("验证码错误");
        }
        if (commonUser == null) {
            return new Result().error("账号不存在");
        } else {
            return new Result().success("登录成功");
        }
    }

//    @ApiOperation(value = "注册身份验证")
//    @PostMapping("/registerFindUserByPhone")
//    @NoAuthentication
//    @ResponseBody
//    @CrossOrigin
//    public Result registerFindUserByPhone(String phone) {
//        QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("state", 0);
//        queryWrapper.eq("deleted", 1);
//        queryWrapper.eq("cuser_phone", phone);
//        final CommonUser commonUser = commonUserService.getOne(queryWrapper);
//        if (!(commonUser == null)) {
//            return new Result().error("手机号已注册");
//        }
//        redisTemplate.opsForValue().set(phone + "commonUser", commonUser, 60 * 5, TimeUnit.SECONDS);
//        return new Result().success().put(commonUser);
//    }

    @ApiOperation(value = "注册")
    @PostMapping("/register")
    @NoAuthentication
    @ResponseBody
    @CrossOrigin
    public Result register(String phone, String code, String idcard, String pwd) {
        System.out.println(phone);

        String msgcode = (String) redisTemplate.opsForValue().get(phone + "msgcode");
        if (!code.equals(msgcode)) {
            return new Result().error("验证码错误");
        }
        CommonUser commonUser = new CommonUser();
        commonUser.setCuserAccount(phone);
        commonUser.setCuserCard(idcard);
        commonUser.setCuserPassword(md5.encrypt(pwd));
        commonUser.setCuserPhone(phone);
        commonUser.setDeleted(1);
        commonUser.setState(2);

        QueryWrapper<CommonUser> commonUserQueryWrapper = new QueryWrapper<>();
        commonUserQueryWrapper.eq("cuser_phone", phone)
                .eq("state", 0);

        if (commonUserService.getOne(commonUserQueryWrapper) != null) {
            return new Result().error("手机号已注册!");
        }

//        QueryWrapper<Schoolroll> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("suser_card", idcard);
//        Schoolroll schoolroll = schoolrollService.getOne(queryWrapper);
        //没有学籍信息的话需要发给后台审核
//        if (schoolroll == null) {
//            return new Result().success(300,"学籍信息不存在!");
//        } else {
//            //此处还有把学籍信息赋值给校友信息的操作,没有学籍表,暂时搁置
//
//
//
//
//
//
//            commonUser.setState(0);
//            Mail mail = new Mail();
//            mail.setTitle("注册成功!");
//            mail.setContent("您已注册为平院校友,欢迎您的加入");
//            mail.setTo(commonUser.getCuserEmail());
//            if (produceService.send(mail)) {
//                log.info("邮件发送成功,已经进入队列");
//            } else {
//                log.error("邮件发送失败");
//            }
//            return new Result().success("注册成功");
//        }
        commonUserService.save(commonUser);
        //用户表也需要同步添加校友,设置为软删除
        User user = new User();
        user.setUserAccount(commonUser.getCuserAccount());
        user.setUserPassword(md5.encrypt(commonUser.getCuserPassword()));
        user.setUserDelFlag(0);
        user.setUserState(1);
        user.setUserCreatetime(DateUtil.formatTime(new Date()));
        user.setUserUpdateTime(DateUtil.formatTime(new Date()));
        userService.save(user);
        return new Result().success("注册成功");
    }

    @ApiOperation(value = "认证")
    @PostMapping("/authentication")
    @NoAuthentication
    @ResponseBody
    @CrossOrigin
    public Result authentication(@RequestBody Map map) {
        String phone = (String) map.get("phone");
        String name = (String) map.get("name");
        String email = (String) map.get("email");
        String idcard = (String) map.get("idcard");
        String stdnum = (String) map.get("stdnum");
        String pmajor = (String) map.get("pmajor");
        //时间不好说怎么弄
        Date starttime = (Date) map.get("starttime");
        Date endttime = (Date) map.get("endtime");

        String faculty = (String) map.get("faculty");
        CommonUser commonUser = new CommonUser();
        commonUser.setCuserAccount(phone);
        commonUser.setCuserName(name);
        commonUser.setCuserEmail(email);
        commonUser.setCuserCard(idcard);
        commonUser.setCuserStdnum(stdnum);
        commonUser.setCuserMajor(pmajor);
        commonUser.setCuserStartTime(DateUtil.formatMonth(starttime));
        commonUser.setCuserEndTime(DateUtil.formatMonth(endttime));
        commonUser.setCuserFaculty(faculty);
        commonUser.setState(2);
        commonUser.setDeleted(1);
        commonUserService.save(commonUser);
        return new Result().success();
    }

    @ApiOperation(value = "重置密码身份验证")
    @PostMapping("/resetFindUserByPhone")
    @NoAuthentication
    @ResponseBody
    @CrossOrigin
    public Result resetFindUserByPhone(String phone) {
        QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 0);
        queryWrapper.eq("deleted", 1);
        queryWrapper.eq("cuser_phone", phone);
        final CommonUser commonUser = commonUserService.getOne(queryWrapper);
        if (commonUser == null) {
            return new Result().error("查无此账号");
        }

        Mail mail = new Mail();
        mail.setTitle("重置密码");
        mail.setContent("您的账号正在尝试重置密码,请确认是您本人操作");
        mail.setTo(commonUser.getCuserEmail());
        if (produceService.send(mail)) {
            log.info("邮件发送成功,已经进入队列");
        } else {
            log.error("邮件发送失败");
        }
        redisTemplate.opsForValue().set(phone + "commonUser", commonUser, 60 * 5, TimeUnit.SECONDS);
        return new Result().success().put(commonUser);
    }

    @ApiOperation(value = "重置密码")
    @PostMapping("/pwdReset")
    @NoAuthentication
    @ResponseBody
    @CrossOrigin
    public Result pwdReset(String phone, String newpwd) {
        CommonUser commonUser = (CommonUser) redisTemplate.opsForValue().get(phone + "commonUser");
        commonUser.setCuserPassword(newpwd);
        if (!commonUserService.updateById(commonUser)) {
            return new Result().error("重置失败");
        } else {
            Mail mail = new Mail();
            mail.setTitle("重置密码成功");
            mail.setContent("密码已重置,请牢记密码");
            mail.setTo(commonUser.getCuserEmail());
            if (produceService.send(mail)) {
                log.info("邮件发送成功,已经进入队列");
            } else {
                log.error("邮件发送失败");
            }
            return new Result().success("重置成功");
        }
    }


    @ApiOperation(value = "获取所有院系")
    @GetMapping("/listAllFaculty")
    @NoAuthentication
    //@RequiresPermissions("")
    @ResponseBody
    @CrossOrigin
    public Result getAllFaculty() {
        List<Faculty> list = facultyService.list(null);
        return new Result().success().put(list);
    }

    @ApiOperation(value = "通过院系获取校友")
    @GetMapping("/listCommonUserByFaculty")
    @NoAuthentication
    @ResponseBody
    @CrossOrigin
    public Result getCommonUserByFaculty(Integer id) {
        List<CommonUser> list = commonUserService.list(new QueryWrapper<CommonUser>().eq("cuser_faculty",facultyService.getById(id).getFacultyName()));
        return new Result().success().put(list);
    }
}
